/**
 * Created with IntelliJ IDEA.
 * Description:找到数组中第 k大的元素
 * User: YJ
 * Date: 2024-4-06
 * Time: 15:34
 */
public class FindKthLargestExe {

    public static void main(String[] args) {
        int[] arr1 = new int[] {3,2,1,5,6,4};
        int[] arr2 = new int[] {3,2,3,1,2,4,5,5,6};
        System.out.println(findKthLargest(arr1, 2));//5
        System.out.println(findKthLargest(arr2, 4));//4
    }

    public static int findKthLargest(int[] array, int k) {
        //创建小顶堆
        MinHeap minHeap = new MinHeap(k);
        //将数组前k个元素加入小顶堆
        for (int i = 0; i < k; i++) {
            minHeap.offer(array[i]);
        }
        //剩余的元素，与堆顶元素进行比较
        //大于堆顶元素，则替换
        //小于堆顶元素，则略过
        for (int i = k; i < array.length; i++) {
            if (array[i] > minHeap.peek()) {
                minHeap.replace(array[i]);
            }
        }
        return minHeap.peek();
    }
}
